package HomeService

import (
	"context"
	"gdshop-back-end-go/client-api/app/request/HomeReq"
	"gdshop-back-end-go/common/response"
	"gdshop-back-end-go/common/wxpayHelper"
	"github.com/shenghui0779/gochat/mp"
	"github.com/shenghui0779/gochat/oa"
)

func WechatMpLogin(ctx context.Context, parames *HomeReq.WechatMpLogin) *response.JsonResponse {
	wxmp := wxpayHelper.GetWxMp()

	session, err := wxmp.Code2Session(ctx, parames.Code)
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	var dest mp.UserInfo
	err = wxmp.DecryptAuthInfo(&dest, session.SessionKey, parames.Iv, parames.EncryptedData)
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}

	wechatInfo := oa.AuthUser{
		OpenID:     session.OpenID,
		UnionID:    dest.UnionID,
		Nickname:   dest.NickName,
		Province:   dest.Province,
		City:       dest.City,
		Country:    dest.Country,
		HeadImgURL: dest.AvatarURL,
	}
	if dest.Gender == 0 {
		wechatInfo.Sex = 0
	}
	if dest.Gender == 1 {
		wechatInfo.Sex = 1
	}
	if dest.Gender == 2 {
		wechatInfo.Sex = 2
	}

	return WechatLoginByAuthUser(ctx, session.OpenID, &wechatInfo)
}
